import axios from "axios";

// 获取API服务器地址
export const getAPIServerURL = () => {
  // 在开发环境中，使用相对路径让 Vite 代理工作
  // 在生产环境中，这个可以从配置文件或构建时注入
  if (import.meta.env.DEV) {
    return ""; // 空字符串表示相对路径
  }
  return "http://localhost:8080";
};

// 获取WebSocket服务器地址
export const getWebSocketServerURL = () => {
  const apiURL = getAPIServerURL();
  const protocol = apiURL.startsWith('https:') ? 'wss:' : 'ws:';
  const host = apiURL.replace(/^https?:\/\//, ''); // 移除协议前缀
  return `${protocol}//${host}`;
};

export const api = axios.create({
  baseURL: `${getAPIServerURL()}/api/v1`,
  timeout: 5000,
});

// Domain/Virtual Machine APIs
export const listDomains = () => api.get("/domains?inactive=true");
export const getDomain = (uuid: string) => api.get(`/domains/${uuid}`);
export const startDomain = (uuid: string) =>
  api.post(`/domains/${uuid}/action`, { action: "start" });
export const stopDomain = (uuid: string) =>
  api.post(`/domains/${uuid}/action`, { action: "shutdown" });
export const forceStopDomain = (uuid: string) =>
  api.post(`/domains/${uuid}/action`, { action: "destroy" });
export const pauseDomain = (uuid: string) =>
  api.post(`/domains/${uuid}/action`, { action: "suspend" });
export const resumeDomain = (uuid: string) =>
  api.post(`/domains/${uuid}/action`, { action: "resume" });
export const restartDomain = (uuid: string) =>
  api.post(`/domains/${uuid}/action`, { action: "reboot" });
export const deleteDomain = (uuid: string) =>
  api.delete(`/domains/${uuid}`);
export const forceDeleteDomain = (uuid: string) =>
  api.delete(`/domains/${uuid}?force=true`);

// 更新虚拟机配置
export const updateDomain = (uuid: string, updateConfig: any) =>
  api.put(`/domains/${uuid}`, updateConfig);

// Create Virtual Machine API
export const createDomain = (domainConfig: any) =>
  api.post("/domains", domainConfig);

// Create Virtual Machine with Wizard API
export const createDomainWithWizard = (wizardConfig: any) =>
  api.post("/domains/wizard", wizardConfig);

// Helper APIs for VM creation
export const checkDomainName = (name: string) =>
  api.get(`/domains/check-name?name=${name}`);

export const getHostResources = () =>
  api.get("/host/resources");

export const validateISO = (isoPath: string) =>
  api.post("/iso/validate", { path: isoPath });

// Snapshot APIs
export const listSnapshots = (domainName: string) =>
  api.get(`/snapshots?domain=${domainName}`);
export const getSnapshot = (domainName: string, snapshotName: string) =>
  api.get(`/snapshots/${domainName}/${snapshotName}`);
export const createSnapshot = (domainName: string, snapshotConfig: any) =>
  api.post(`/snapshots/${domainName}`, snapshotConfig);
export const revertSnapshot = (domainName: string, snapshotName: string, force: boolean = false) =>
  api.post(`/snapshots/${domainName}/${snapshotName}/revert`, { force });
export const deleteSnapshot = (domainName: string, snapshotName: string, deleteChildren: boolean = false) =>
  api.delete(`/snapshots/${domainName}/${snapshotName}`, { data: { delete_children: deleteChildren } });

// Storage APIs
export const listStoragePools = () => api.get("/storage/pools");
export const getStoragePool = (uuid: string) => api.get(`/storage/pools/${uuid}`);
export const createStoragePool = (pool: any) => api.post("/storage/pools", pool);
export const deleteStoragePool = (uuid: string) => api.delete(`/storage/pools/${uuid}`);

export const listVolumes = (poolUUID: string) =>
  api.get(`/storage/pools/${poolUUID}/volumes`);
export const getVolume = (poolUUID: string, volumeName: string) =>
  api.get(`/storage/pools/${poolUUID}/volumes/${volumeName}`);
export const createVolume = (poolUUID: string, volume: any) =>
  api.post(`/storage/pools/${poolUUID}/volumes`, volume);
export const deleteVolume = (poolUUID: string, volumeName: string) =>
  api.delete(`/storage/pools/${poolUUID}/volumes/${volumeName}`);

// Storage Pool Operations
export const startStoragePool = (uuid: string) =>
  api.post(`/storage/pools/${uuid}/start`);

export const stopStoragePool = (uuid: string) =>
  api.post(`/storage/pools/${uuid}/stop`);

export const refreshStoragePool = (uuid: string) =>
  api.post(`/storage/pools/${uuid}/refresh`);

// Network APIs
export const listNetworks = () => api.get("/networks");
export const getNetwork = (name: string) => api.get(`/networks/${name}`);
export const createNetwork = (network: any) => api.post("/networks", network);
export const deleteNetwork = (name: string) => api.delete(`/networks/${name}`);
export const startNetwork = (name: string) => api.post(`/networks/${name}/start`);
export const stopNetwork = (name: string) => api.post(`/networks/${name}/stop`);

// VNC and Console APIs
export const getVNCInfo = (uuid: string) => api.get(`/domains/${uuid}/vnc`);

// Console WebSocket URL helper - now uses the URL provided by backend
export const getConsoleWebSocketURL = (uuid: string, consoleType = 'console', consoleWebSocketURL?: string | null) => {
  // 使用后端API服务器的WebSocket地址，而不是当前页面的地址
  const wsServerURL = getWebSocketServerURL();

  // 如果后端提供了控制台WebSocket URL，则使用它
  if (consoleWebSocketURL) {
    // 使用后端提供的路径，但使用API服务器的协议和主机
    return `${wsServerURL}${consoleWebSocketURL}?type=${consoleType}`;
  }

  // 回退到原始实现
  return `${wsServerURL}/api/v1/domains/${uuid}/console?type=${consoleType}`;
};